# Copyright (c) 2005,2006,2007 Dynamic Solutions Inc. (support@dynamic-solutions.com)
#
# This file is part of DataZoomer.
#
# DataZoomer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# DataZoomer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""DataZoomer Page"""

from dzutil import link_to, url_for
from zoom import zoomer
import os, dzentity, dzfill, dzutil, dzml
import dzresponse

class Page(dzentity.Entity):
    def __init__(self,content='no content',**keywords):
        dzentity.Entity.__init__(self,keywords)
        self.template_name = 'default'
        self.content  = content
        self.callback = None

        # page components
        self.parts     = []
        self.messages  = []
        self.warnings  = []
        self.actions   = []
        self.html_head = []

        self.DZ      = zoomer.main_url
        self.ROOT    = zoomer.root_url
        self.SID     = zoomer.sid
        self.APP     = zoomer.app.name
        self.URL     = dzutil.url_for(app='home')

        self.title   = zoomer.app.title
        self.subtitle = ''

        self.main_menu_items = self.calc_main_menu_items()

    def calc_main_menu_items(self):
        selected_apps = []
        links = []
        for app in zoomer.user_apps:
            if (app.visible and not app.system_app and app.status=='P'):
                link = link_to(app.title,title=app.title,app=app.name,con='')
                if app.name == zoomer.app.name:
                    url = dzutil.url_for(app=app.name,con='')
                    link = '<a class=selected_item href="%s">%s</a>' % (url,app.title)
                    links.append('<li class=selected_item>%s</li>\n' % link)
                else:
                    links.append('<li>%s</li>\n'%link)
                selected_apps.append(app.name)
        for app in zoomer.user_apps:
            if (app.visible and app.name==zoomer.app.name and not app.name in selected_apps):
                link = link_to(app.title,title=app.title,app=app.name,con='')
                if app.name == zoomer.app.name:
                    url = dzutil.url_for(app=app.name,con='')
                    link = '<a class=selected_item href="%s">%s</a>' % (url,app.title)
                    links.append('<li class=selected_item>%s</li>\n' % link)
                else:
                    links.append('<li>%s</li>\n'%link)
        return links

    def as_li(self,item,selected=0):
        if item:
            return '<li %s>%s</li>' % (selected and 'class="selected_item"' or '',item)

    def as_ul(self,items):
        if items:
            l = ['<ul>'] + [self.as_li(item) for item in items] + ['</ul>']
        else:
            l = []
        return ''.join(l)

    def get_APPCSS(self):
        return ''

    def get_POWERED_BY(self):
        return 'powered by <a href="http://www.datazoomer.org">DataZoomer</a>'

    def get_POWEREDBY(self):
        return self.get_POWERED_BY()

    def render_panel(self,content,**keywords):
        return content

    def get_USERID(self):
        return zoomer.user_id

    def get_LOGINID(self):
        return zoomer.loginid

    def get_USER_FIRST_NAME(self):
        from common.models.user import Users
        return Users().current().FIRSTNAME #zoomer.loginid

    def get_THEME(self):
        return '%s' % zoomer.theme_name
        
    def get_SITE_NAME(self):
        return zoomer.name

    def get_COMPANY_NAME(self):
        return zoomer.site_owner

    def get_STYLES(self):
        return '<link rel="stylesheet" href="%(theme_url)sshared/dz.css" type="text/css" />\n<link rel="stylesheet" href="%(theme_url)s%(theme)s/styles/style.css" type="text/css" />' % dict(theme=self.THEME,theme_url=zoomer.theme_url)

    def get_IMG(self):
        return '%(theme_url)s/%(theme)s/images/' % dict(theme_url=zoomer.theme_url,theme=zoomer.theme_name)

    def get_ACTIONS(self):
        actions = zoomer.app.actions + self.actions
        return self.as_ul(actions)

    def get_HTML_HEAD(self):
        try:
            result = ''.join(self.html_head)
        except:
            result = '<!-- an error occured while rendering HTML_HEAD tag -->'
        return result

    def get_MAINMENU_TITLE(self):
        return (len(self.main_menu_items)>0) and 'Applications' or ''

    def get_APPMENU_TITLE(self):
        return ''

    def get_TITLE(self):
        return self.title

    def get_SUBTITLE(self):
        return self.subtitle

    def get_WARNING(self):
        warnings = zoomer.session.warnings
        zoomer.session.warnings = []
        if warnings and len(warnings):
            return '<ul>%s</ul>' % ''.join(['<li>%s' % item for item in warnings])
        else:
            return ''

    def get_MESSAGE(self):
        messages = zoomer.session.messages
        zoomer.session.messages = []
        if messages and len(messages):
            return '<ul>%s</ul>' % ''.join(['<li>%s' % item for item in messages])
        else:
            return ''

    def get_MAINPANEL(self):
#         lines = self.content.splitlines(1)
#         if len(lines) > 1:
#             return self.render_panel(''.join(lines[1:]))
#         return ''
        return self.render_panel(self.content)

    def get_SITE_TITLE(self):
        return zoomer.name

    def get_SITE_SLOGAN(self):
        return zoomer.slogan

    def get_APP_TITLE(self):
        return zoomer.app.title

    def get_APP_SUBTITLE(self):
        return zoomer.app.subtitle

    def get_FOOTER(self):
        return self.POWEREDBY

    def get_MAINMENU(self):
        return self.get_MAIN_MENU()

    def get_APPMENU(self):
        return self.get_APP_MENU()

    def get_MAIN_MENU(self):
        return '<ul>' + ''.join(self.main_menu_items) + '</ul>'

    def get_APP_MENU(self):
        result = []
        if zoomer.app.controllers:
            result.append('<UL>')
            for item in zoomer.app.controllers:
                link = link_to(item[1],app=zoomer.app.name,con=item[0])
                if item[0]==zoomer.app.controller_name:
                    url = dzutil.url_for(app=zoomer.app.name,con=item[0])
                    link = '<a class=selected_item href="%s">%s</a>\n' % (url,item[1])
                    result.append('<LI class=selected_item>%s</LI>' % link)
                else:
                    result.append('<LI>%s</LI>' % link)
            result.append('</UL>')
        return ''.join(result)

    def get_APP_ACTIONS(self):
        result = []
        if zoomer.app.actions:
            if self.APPMENU_TITLE:
                result.append('<H1>%s</H1>' % self.APPMENU_TITLE)

            result.append('<UL>')
            for item in zoomer.app.actions:
                if 'con=subject' in item:
                    result.append('<LI>%s</LI>' % item.replace('href=','class=selected_item href='))
                else:
                    result.append('<LI>%s</LI>' % item)
            result.append('</UL>')

#            result.append('<UL>%s</UL>' % (''.join(['<LI>%s</LI>' % str(item) for item in zoomer.app.actions])))
        return ''.join(result)

    def get_LOGIN_LOGOUT(self):
        for app in zoomer.system_apps:
            if app.name == 'login' and not zoomer.authenticated:
                return self.as_li('<A href="%s" style="color:#FFFF99;">%s</A>' % (url_for(app=app.name,con=''),app.title))
            elif app.name == 'logout' and zoomer.authenticated:
                return self.as_li('<A href="%s" style="color:#FFFF99;">%s</A>' % (url_for(app=app.name,con=''),app.title))
        return ''

    def get_SYSTEM_MENU(self):
        links = []
        for app in zoomer.system_apps:
            if (zoomer.authenticated and not app.name in ['login','register']) or (not zoomer.authenticated and app.name not in ['logout']):
                links.append(link_to(app.title,title=app.title,app=app.name,con=''))
        return self.as_ul(links)

    def get_SYSTEMMENU(self):
        return self.get_SYSTEM_MENU()

    def get_SITE_DESCRIPTION(self):
        path = os.path.join(zoomer.data_path,'content','snippets','site_description.txt')
        if os.path.exists(path):
            t = open(path,'r').read()
        else:
            t = ''
        return t

    def get_SITE_KEYWORDS(self):
        path = os.path.join(zoomer.data_path,'content','snippets','site_keywords.txt')
        if os.path.exists(path):
            t = open(path,'r').read()
        else:
            t = ''
        return t

    def SET(self,*args,**keywords):
        t = ''
        if 'theme' in keywords:
            zoomer.theme_name = keywords.get('theme')

        if 'template' in keywords:
            name = keywords.get('template')
            if self.template_exists(name):
                self.template_name = name
                zoomer.debug('template set to %s' % name)
            else:
                zoomer.debug('template %s does not exist in theme %s' % (name,zoomer.theme_name))
        return t

    def SNIPPET(self,*args,**keywords):
        def handle(tag,*args):
            if zoomer.app.name == 'content' and zoomer.webvars.page==args[0]:
                url = dzutil.url_for(app='content',page=args[0])
                link = '<a class=selected_item href="%s">%s</a>\n' % (url,args[1])
                return ('<LI class=selected_item>%s</LI>' % link)
            else:
                return dzutil.link_to(args[1],app='content',page=args[0])

        if 'name' in keywords:
            path = os.path.join(zoomer.data_path,'content','snippets','%s.txt' % keywords['name'])
            if os.path.exists(path):
                data = dzfill.fill(open(path,'r').read(),self)
                t = dzml.dzml(data,callback=handle)
            else:
                t = 'snippet <i>"%s"</i> missing' % (keywords['name'])
        else:
            t = 'snippet name missing'
        return t

    def get_PARTS(self):
        return ''.join(self.parts)

    def get_ICON(self):
        return '<img height=44 src="%(theme_url)s/default/icons/%(icon)s.png" alt="" border="0">' % dict(theme_url=zoomer.theme_url,icon=zoomer.app.iconname)

    def get_PANEL1(self):
        return self.render_panel(self.panel1)

    def get_PANEL2(self):
        return self.render_panel(self.panel2)

    def get_PANEL3(self):
        return self.render_panel(self.panel3)

    def template_filename(self,name):
        return '%s/%s/templates/%s.htm' % (zoomer.theme_path,zoomer.theme_name,name)

    def template_exists(self,name):
        return os.path.exists(self.template_filename(name))

    def render_content(self,**keywords):
        def get_template_path():
            return '%s/%s/templates/' % (zoomer.theme_path,zoomer.theme_name)

        def get_template():
            if self.template_exists(self.template_name):
                return open(self.template_filename(self.template_name),'r').read()
            else:
                return open(self.template_filename('default'),'r').read()

        def calc_wiki_menu():
            site = keywords.get('site','')
            key  = keywords.get('key',self.name)
            return '<div class=wikimenu><br><br><hr>%s&nbsp;&nbsp;%s&nbsp;&nbsp;%s</div>' % ( \
                link_to('Edit',action='edit_page',site=site,key=key),
                link_to('Normal',action='show_page',site=site,key=key,preview=0),
                link_to('List',action='pages',key=site))

        self.wiki_menu = calc_wiki_menu()

        tmp = dzfill.fill(self.content,self) # to set template
        content = dzfill.fill(get_template(),self)

        old_files_location = '%s_files/' % self.template_name
        new_files_location = '%(theme_url)s%(theme)s/templates/%(template)s_files/' % dict(theme_url=zoomer.theme_url,theme=zoomer.theme_name,template=self.template_name)

        return content.replace(old_files_location,new_files_location)


    def render(self,**keywords):
        return dzresponse.HTMLResponse(self.render_content(**keywords))



